  // @ts-nocheck
import { ref, onMounted, watchEffect } from 'vue';
import OpenSeadragon from 'openseadragon';
import { fabric } from 'fabric';
import useImgInfo from './useImgInfo';
import useUtils from "./useUtils";
import {useRoute} from 'vue-router';
import { dataInfo, OpenSeadragonOptions } from "./useInitData";
import * as Store from '@/store';

const useInit = (EventHooks: ContentEvent.EventHooks, initData: Function) => {
  const UtilsHooks = useUtils();
  const route = useRoute();
  const readonly = (route.query.type === 'query' ? true : false)
  const InfoHooks = useImgInfo();
  // const EventHooks = useEvents(dataInfo, getActualNum, changePoint, initData, getMarkObj, isDefault);
  const FilmRead = Store.useFilmRead();
  const load = ref(false);
  // const FilmReadHead = Store.useFilmReadHeader();
  // const FilmReadLeft = Store.useFilmReadLeft();
  // const FilmReadRight = Store.useFilmReadRight();
  // 初始化创建切片预览对象
  // const chunkData = [
  //   {i:"67yj5xqg-rnpw-2lvz-twg2-600i0rcwdoco",r:1,c:1,w:200,h:200},
  //   {i:"8j7wwp04-lz9n-ifrb-c7cn-a8ky1todxd90",r:2,c:1,w:200,h:200},
  //   {i:"g1iwt1o8-lx15-n7kr-81vj-e5vxw9q80qkt",r:3,c:1,w:200,h:200}
  // ]; 
  // const colors = ['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c'];
  const initViewer = (url: string) => {
    OpenSeadragonOptions.tileSources = url + ".dzi";
    dataInfo.viewer = new OpenSeadragon.Viewer(OpenSeadragonOptions);
    // dataInfo.viewer.addTiledImage({
    //   tileSource: url
    // })
    dataInfo.mouseTracker = new OpenSeadragon.MouseTracker({
      element: 'viewer',
    });
    // chunkData.forEach(function(chunk,i) {
    //   var chunkLabel = document.createElement("div");
    //   chunkLabel.id = chunk.i;
    //   chunkLabel.className = "chunk no-distress";
    //   dataInfo.viewer.addOverlay({
    //     element: chunkLabel,
    //     location: new OpenSeadragon.Rect(chunk.c, chunk.r, chunk.w, chunk.h)
    //   });
    //   var tracker = new OpenSeadragon.MouseTracker({
    //     element: chunkLabel,
    //     clickHandler: function(event) {
    //       console.log(chunk.c, chunk.r)
    //     }
    //   });
    // });
    // const overlay = new OpenSeadragon.CanvasOverlayHd(viewer, {
    //   onRedraw: function (opts) {
    //     const context = opts.context;
    //     context.fillStyle = colors[opts.index];
    //     context.beginPath();
    //     context.arc(150, 150, 150, 0, Math.PI * 2, true);
    //     context.fill();
    //   }
    // });
  };

  const initCommon = async (url: string) => {
    dataInfo.slideInfo = InfoHooks.info.value;

    initViewer(url);
    initMark();
    UtilsHooks.initZoom();
    load.value = true;
    dataInfo.viewer.addHandler('update-viewport', resizeCanvas);
    const res = await new Promise(resolve => {
      dataInfo.viewer.addHandler('open', (e) => {
        resize();
        load.value = false;
        resolve(true);
      });
    })
    dataInfo.viewer.addHandler('resize', resize);
    // res && initData();
    // 如果不加计时器，会导致数据渲染异常 todo
    setTimeout(() => {
      initData();
    }, 500);
  }

  let fabricToolContainer: HTMLElement;
  let containerWidth = ref(1);
  let containerHeight = ref(1);

  // 初始化标注画布
  const initMark = () => {
    // 注销标记画布
    dataInfo.frabicCanvas && dataInfo.frabicCanvas.dispose();
    // 创建画布容器
    fabricToolContainer = document.createElement('div');
    fabricToolContainer.setAttribute('id', 'canvasDiv');
    fabricToolContainer.style.position = 'absolute';
    fabricToolContainer.style.left = fabricToolContainer.style.top = '0';
    fabricToolContainer.style.width = fabricToolContainer.style.height = '100%';
    // 将容器放进 openSeadragon 中
    dataInfo.viewer!.canvas.appendChild(fabricToolContainer);
    // 创建画布
    dataInfo.fabricToolCanvas = document.createElement('canvas');
    dataInfo.fabricToolCanvas.setAttribute('id', 'canvas');
    fabricToolContainer.appendChild(dataInfo.fabricToolCanvas);
    dataInfo.frabicCanvas = new fabric.Canvas('canvas', {
      centeredScaling: false, // 全局所有元素都生效
      // 选择是否完全包含
      selectionFullyContained: false,
      // 是否可按住画布进行缩放
      enableRetinaScaling: false,
      // 是否可选择 false为不可以被选择 true可以被选择
      selection: !readonly,
      // preserveObjectStacking: true,
      // 精简输出json标注对象
      includeDefaultValues: false,
      // 放大到一定倍数，会跳过部分渲染，需要关闭
      skipOffscreen: false, //跳过当前视口中未包含的对象的渲染。在画布拥挤和使用缩放/平移的应用程序中可能会有很大帮助如果对象边界框的一角在画布上，则对象将被渲染。
      // 是否以中心店缩放 默认是true以中心点缩放 false不是中心点
      // centeredScaling: false,
      // 对象是都可以固定一边被进行拉伸 默认是false true为可以固定
      // uniScaleTransform: true
      // 设置默认框选样式的选中色
      // selectionColor: 'rgba(255, 255, 255, 0)',
      fireRightClick: true, // 启用右键，button的数字为3
      stopContextMenu: true, // 禁止默认右键菜单
      targetFindTolerance: 3,//hover宽度
      // renderOnAddRemove: false,
    });
    // 设置笔刷颜色和宽度
    dataInfo.frabicCanvas.freeDrawingBrush.color = dataInfo.pencilColor;
    dataInfo.frabicCanvas.freeDrawingBrush.width = dataInfo.pencilWidth;
    dataInfo.frabicCanvas.setWidth(dataInfo.viewer.container.clientWidth);
    dataInfo.frabicCanvas.setHeight(dataInfo.viewer.container.clientHeight);
    
    // 绑定监听事件用于大图渲染校正canvas标注画布
    /*dataInfo.viewer && (dataInfo.viewer.zoomPerScroll = 1.1);
    dataInfo.viewer && (dataInfo.viewer.panHorizontal = true);
    dataInfo.viewer && (dataInfo.viewer.panVertical = true);
    dataInfo.frabicCanvas.isDrawingMode = false
    dataInfo.isDefault = false;
    dataInfo.doDrawing = false;*/
    dataInfo.currentToolItem = {}
    UtilsHooks.setZoomActive()
    EventHooks.frabicMouseEvent();
    EventHooks.pictureEvent();
    EventHooks.keyDownEvent();
  };

  // 初始重置画布
  const resize = () => {
    containerWidth.value = dataInfo.viewer.container.clientWidth;
    containerHeight.value = dataInfo.viewer.container.clientHeight;
    fabricToolContainer.setAttribute('width', String(containerWidth.value));
    fabricToolContainer.setAttribute('height', String(containerHeight.value));
    dataInfo.fabricToolCanvas.setAttribute('width', String(containerWidth.value));
    dataInfo.fabricToolCanvas.setAttribute('height', String(containerHeight.value));
    dataInfo.frabicCanvas.setWidth(containerWidth.value);
    dataInfo.frabicCanvas.setHeight(containerHeight.value);
  };

  // 修正画布
  const resizeCanvas = () => {
    // return;
    const origin = new OpenSeadragon.Point(0, 0);
    const viewportWindowPoint =
      dataInfo.viewer.viewport.viewportToWindowCoordinates(origin);
    // const x = Math.round(viewportWindowPoint.x);
    // const y = Math.round(viewportWindowPoint.y);
    const x = viewportWindowPoint.x;
    const y = viewportWindowPoint.y;
    const canvasOffset = fabricToolContainer.getBoundingClientRect();
    const pageScroll = OpenSeadragon.getPageScroll();
    //缩放更平滑
    dataInfo.frabicCanvas.zoomToPoint(new fabric.Point(
        canvasOffset.left - x + pageScroll.x,
        canvasOffset.top - y + pageScroll.y
    ),1)
  };
  
  return {
    initCommon,
    resizeCanvas,
    getInfo: InfoHooks.getInfo,
    getImageUrl: InfoHooks.getImageUrl
  };
};

export default useInit;
